package com.itmk.web.wx_user.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itmk.annotation.Auth;
import com.itmk.jwt.JwtUtils;
import com.itmk.utils.ResultUtils;
import com.itmk.utils.ResultVo;
import com.itmk.web.wx_user.entity.*;
import com.itmk.web.wx_user.service.WxUserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/wxUser")
public class WxUserController {
    @Autowired
    private WxUserService wxUserService;

    @Autowired
    private JwtUtils jwtUtils;
    @CrossOrigin
    @PostMapping("/register")
    public ResultVo register(@RequestBody WxUser user){
        //判断用户是否被占用
       LambdaQueryWrapper<WxUser> queryWrapper = new LambdaQueryWrapper<>();
       queryWrapper.eq(WxUser::getUsername,user.getUsername());
       WxUser one = wxUserService.getOne(queryWrapper);
       if (one!=null){
           return ResultUtils.error("用户名被占用");
       }
       //存入数据库
       //密码加密存储
       user.setUserId(wxUserService.maxId());
       user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
       if (wxUserService.save(user)) {
           return ResultUtils.success("注册成功");
       }
       return ResultUtils.error("注册失败");
   }

   //登录
   @CrossOrigin
   @PostMapping("/login")
    public ResultVo login(@RequestBody WxUser user){
       LambdaQueryWrapper<WxUser> queryWrapper = new LambdaQueryWrapper<>();
       queryWrapper.eq(WxUser::getUsername,user.getUsername())
               .eq(WxUser::getPassword,DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
      WxUser wxUser = wxUserService.getOne(queryWrapper);
      if(wxUser ==null){
          return ResultUtils.error("密码错误/用户名错误");
      }
      if(wxUser.getStatus().equals("1")){
          return ResultUtils.error("账户被封杀100年");
      }
      else {
          LoginVo vo = new LoginVo();
          vo.setNickName(wxUser.getNickName());
          vo.setPhone(wxUser.getPhone());
          vo.setUserId(wxUser.getUserId());
          Map<String,String> map = new HashMap<>();
          map.put("userId",Long.toString(wxUser.getUserId()));
          vo.setToken(jwtUtils.generateToken(map));
          return ResultUtils.success("登录成功",vo);
      }
  }
  //分页查询
  @Auth
  @CrossOrigin
  @GetMapping("/list")
  public ResultVo getList( WxUserParm parm){
      Page<WxUser> page = new Page<>();
      LambdaQueryWrapper<WxUser> queryWrapper =  new LambdaQueryWrapper<>();
      queryWrapper.like(StringUtils.isNotEmpty(parm.getPhone()),WxUser::getPhone,parm.getPhone())
              .orderByDesc(WxUser::getUsername);
      Page<WxUser> userPage = wxUserService.page(page, queryWrapper);
      return ResultUtils.success("查询成功",userPage);
  }
    @Auth
    @CrossOrigin
    @PostMapping("/stopUser")
  public ResultVo stopUser(@RequestBody WxUser user){
      LambdaUpdateWrapper<WxUser> wrapper = new LambdaUpdateWrapper<>();
      wrapper.set(WxUser::getStatus,user.getStatus())
              .eq(WxUser::getUserId,user.getUserId());
      if (wxUserService.update(wrapper)){
          return user.getStatus().equals("1")? ResultUtils.success("账号被封杀"):
                  ResultUtils.success("解封");
      }
      return ResultUtils.error("无法封号");
  }

    /* 重置密码
     *
     * @param user
     * @return  2023 12 4
     */
    @Auth
    @CrossOrigin
    @PostMapping("/updatePassword")
    public ResultVo updatePassword(@RequestBody WxUser user){
        String pas = "123456";
        LambdaUpdateWrapper<WxUser> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(WxUser::getPassword, DigestUtils.md5DigestAsHex(pas.getBytes()))
                .eq(WxUser::getUserId,user.getUserId());
        if (wxUserService.update(wrapper)){
            return ResultUtils.success("重置为123456");
        }
        return ResultUtils.error("失败");
    }
    //删除用户
    @Auth
    @CrossOrigin
    @DeleteMapping("/{userId}")
    public ResultVo deleteWxUser(@PathVariable("userId") Long userId){
        if(wxUserService.removeById(userId)){
            return ResultUtils.success("删掉了");
        }
        return ResultUtils.error("删不掉");
    }
 //小程序用户个人信息获取
    @GetMapping("/getInfo")
    public ResultVo getInfo(Long userId){
        WxUser wxUser = wxUserService.getById(userId);
        if (wxUser==null||wxUser.getStatus().equals("1")){
            return ResultUtils.error("账户不存在");
        }
        return ResultUtils.success("用户信息",wxUser);
    }
    //小程序用户编辑个人信息
    @PostMapping("/editInfo")
    public ResultVo editInfo(@RequestBody WxUser user){
          LambdaUpdateWrapper<WxUser> wrapper = new LambdaUpdateWrapper<>();
          wrapper.eq(WxUser::getUserId,user.getUserId())
                  .set(WxUser::getName,user.getName())
                  .set(WxUser::getPhone,user.getPhone())
                  .set(WxUser::getNickName,user.getNickName())
                  .set(WxUser::getPicture,user.getPicture());
          wxUserService.update(wrapper);
          return ResultUtils.success("yse");
    }

    //小程序修改密码
    @PostMapping("/wxupdatePassword")
    public ResultVo wxupdatePassword(@RequestBody UpPsw upPsw){
        WxUser user = wxUserService.getById(upPsw.getUserId());
        if (!user.getPassword().equals(DigestUtils.md5DigestAsHex(upPsw.getOldPassword().getBytes()))){
            return ResultUtils.error("过去密码错误");
        }
        LambdaUpdateWrapper<WxUser> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(WxUser::getUserId,upPsw.getUserId())
                .set(WxUser::getPassword,DigestUtils.md5DigestAsHex(upPsw.getPassword().getBytes()));
        wxUserService.update(wrapper);
        return ResultUtils.success("修改成功");
    }

    //忘记密码
    @PostMapping("/forget")
    public ResultVo forget(@RequestBody ForgetParm parm){
//查询用户是否存在
        QueryWrapper<WxUser> query = new QueryWrapper<>();
        query.lambda().eq(WxUser::getUsername,parm.getUsername())
                .eq(WxUser::getPhone,parm.getPhone());
        WxUser one = wxUserService.getOne(query);
        if(one == null){
            return ResultUtils.error("账户或电话号码不正确!");
        }
//更新条件
        UpdateWrapper<WxUser> update = new UpdateWrapper<>();
        update.lambda().set(WxUser::getPassword,DigestUtils.md5DigestAsHex(parm.getPassword().getBytes()))
                .eq(WxUser::getUsername,parm.getUsername())
                .eq(WxUser::getPhone,parm.getPhone());
        if(wxUserService.update(update)){
            return ResultUtils.success("重置成功!");
        }
        return ResultUtils.error("修改失败!");
    }
}
